const CDP = require('chrome-remote-interface'),
  log = require('../util/log'),
  config = require('../util/config'),
  mongoMng = require('../mng/mongoMng'),
  ocrMng = require('../mng/ocrMng')

var logOnce = true

function connect() {
  CDP({
    port: config.domain == 'etourly.com' ? 9224 : 9222,
    // host: '127.0.0.1'
  }, client => {
    logOnce = true
    if (config.domain == 'zoro.site') {
      resolve(client)
    } else if (config.domain == 'etourly.com') {
      taobaoResolve(client)
    } else {
      taobaoResolve(client)
    }
  }).on('error', err => {
    if(logOnce) {
      logOnce = false
      log(err);
    }
    // require('os').platform() == 'linux' && require('child_process').exec('docker run -d --privileged -p ' + port + ':9222 justinribeiro/chrome-headless')
    setTimeout(connect, 1000)
  });
}

connect()

// 无用了，填图形验证码
async function getAdvLink2Step3(client, code) {
  log('getting advertising link 2 step 3', code)
  const {
    Network,
    Page,
    DOM,
    Runtime,
    Emulation
  } = client;
  var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".getcode-box textarea")'})
  var cnt = result.description.substring(9, result.description.length - 1)
  if (cnt != 0) {
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".getcode-box textarea")[0].value'})
    return new Promise(resolve => {
      resolve(result.value)
      Runtime.evaluate({expression: 'document.querySelectorAll(".dialog-ext-close")[0].click()'})
    })
  }
  var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")'})
  var cnt = result.description.substring(9, result.description.length - 1)
  if (cnt == 0) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(getAdvLink2Step3(client, code))
      }, 1000)
    })
  }
  var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_CodeInput")'})
  var cnt = result.description.substring(9, result.description.length - 1)
  if (cnt == 0) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(getAdvLink2Step3(client, code))
      }, 1000)
    })
  }
  await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_CodeInput")[0].value="' + code + '"'})
  await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_submit")[0].click()'})
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(getAdvLink2Step3(client, code))
    }, 1000)
  })
}

async function screenshot(client) {
  log('screenshotting')
  const {
    Network,
    Page,
    DOM,
    Runtime,
    Emulation
  } = client;
  var result = await DOM.getDocument();
  var rootNodeId = result.root.nodeId
  const {nodeId: bodyNodeId} = await DOM.querySelector({
    selector: 'body',
    nodeId: rootNodeId,
  });
  const {model: {height}} = await DOM.getBoxModel({nodeId: bodyNodeId});
  await Emulation.setVisibleSize({width: 1440, height: height});
  const screenshot = await Page.captureScreenshot({format: 'png'});
  // const buffer = new Buffer(screenshot.data, 'base64');
  // return new Promise(resolve => {
  //   var filename = 'C:\\Users\\Administrator\\Desktop\\output\\' + parseInt(1000 * Math.random()) + '.png'
  //   require('fs').writeFile(filename, buffer, 'base64', err => {
  //     if (err) {
  //       log(err);
  //     }
  //     resolve(filename)
  //   });
  // })
  exports.screenshot = screenshot.data
  setTimeout(() => {
    screenshot(client)
  }, 60000)
}

function taobaoResolve(client) {
  const {
    Network,
    Page,
    DOM,
    Runtime,
    Emulation
  } = client;
  var qrcodeRequestId
  var taobaoBillRequestId
  var taobaoCodeRequestId
  var jdBillRequestId
  var jdCodeRequestId
  Network.requestWillBeSent(obj => {
    if (obj.request.url.indexOf('://img.alicdn.com/tfscom/') != -1) {
      qrcodeRequestId = obj.requestId
    } else if (obj.request.url.indexOf('https://pub.alimama.com/report/getTbkPaymentDetails.json') != -1) {
      taobaoBillRequestId = obj.requestId
    } else if (obj.request.url.indexOf('//pin.aliyun.com/get_img') != -1) {
      taobaoCodeRequestId = obj.requestId
    } else if (obj.request.url == 'https://media.jd.com/rest/report/detail/in/page') {
      jdBillRequestId = obj.requestId
    } else if (obj.request.url.indexOf('https://authcode.jd.com/verify/image') != -1) {
      jdCodeRequestId = obj.requestId
    }
  });
  Network.loadingFinished(async obj => {
    if (obj.requestId == qrcodeRequestId) {
      var result = await Network.getResponseBody({
        requestId: obj.requestId
      })
      var filename = '/tmp/qrcode.png'
      require('fs').writeFile(filename, new Buffer(result.body, 'base64'), 'base64', async err => {
        if (err) {
          log(err);
          return
        }
      })
      exports.qrcode = result.body
      log('请扫二维码')
    } else if (obj.requestId == taobaoBillRequestId) {
      var {result} = await Runtime.evaluate({expression: 'location.href'})
      var href = result.value
      var result = await Network.getResponseBody({
        requestId: obj.requestId
      })
      result = JSON.parse(result.body)
      if(!result.data) {
        log(result)
        exports.busy = false
        return
      }
      log('抓取' + href + '，获得' + result.data.paymentList.length + '个淘宝订单')
      result.data.paymentList.forEach(item => {
        if (mongoMng.db) {
          mongoMng.db.collection('bill').find({
            taobaoTradeParentId: item.taobaoTradeParentId,
            auctionId: item.auctionId
          }).toArray((err, result) => {
            if (err) {
              log(err);
              return;
            }
            if (result.length == 0) {
              log('有新淘宝订单')
              mongoMng.db.collection('bill').insert([item], (err, result) => {
                if (err) {
                  log(err);
                  return;
                }
              });
            } else {
              log('淘宝订单[' + item.taobaoTradeParentId + ',' + item.auctionId + ']，原来状态：' + result[0].payStatus + '，现在状态：' + item.payStatus)
              if (result.length > 1) {
                log('淘宝订单[' + item.taobaoTradeParentId + ',' + item.auctionId + ']有多条记录')
              }
              mongoMng.db.collection('bill').update({
                taobaoTradeParentId: item.taobaoTradeParentId,
                auctionId: item.auctionId
              }, {
                $set: item
              }, (err, result) => {
                if (err) {
                  log(err);
                  return;
                }
              });
            }
          });
        }
      })
      if (result.data.paginator.page < result.data.paginator.lastPage) {
        var page = result.data.paginator.page
        var nextPage = result.data.paginator.nextPage
        var {result} = await Runtime.evaluate({expression: 'location.href'})
        var url = result.value.replace(new RegExp('pageNo=' + page), 'pageNo=' + nextPage)
        log('抓取' + url)
        await Page.navigate({
          url: url
        })
      } else {
        var {result} = await Runtime.evaluate({expression: 'location.href'})
        if (result.value.indexOf('timeId=1') != -1) {
          log('抓取https://pub.alimama.com/myunion.htm#!/report/detail/taoke?pageNo=1&payId=3&timeId=3')
          await Page.navigate({
            url: 'https://pub.alimama.com/myunion.htm#!/report/detail/taoke?pageNo=1&payId=3&timeId=3'
          })
        } else {
          log('获取淘宝订单结束，释放chrome')
          exports.busy = false
        }
      }
    } else if (obj.requestId == taobaoCodeRequestId) {
      var result = await Network.getResponseBody({
        requestId: obj.requestId
      })
      // var filename = '/tmp/code.png'
      // require('fs').writeFile(filename, new Buffer(result.body, 'base64'), 'base64', async err => {
      //   if (err) {
      //     log(err);
      //     return
      //   }
      // })
      exports.code = result.body
      exports.codeRequestId = obj.requestId
      exports.codeText = ''
      // if (!ocrMng.aipOcr) {
      //   return
      // }
      // var result = await ocrMng.aipOcr.generalBasic(result.body)
      // if (result.words_result && result.words_result[0]) {
      //   var code = result.words_result[0].words.replace(/[\r\n\s]/gm, '')
      //   log('[' + obj.requestId + ']识别验证码:' + code)
      //   if (obj.requestId == taobaoCodeRequestId) {
      //     await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_CodeInput")[0].value="' + code + '"'})
      //     await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_submit")[0].click()'})
      //     setTimeout(async () => {
      //       var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#checkcode-state")[0].className'})
      //       if (result.value.indexOf('checkcode-state-wrong') != -1 && obj.requestId == taobaoCodeRequestId) {//换验证码
      //         log('换验证码')
      //         await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_CheckCodeImg1")[0].click()'})
      //       }
      //     }, 2000)
      //   }
      // } else {
      //   log(result)
      //   if (result.error_code == 17) {
      //     ocrMng.switch()
      //     if (!ocrMng.aipOcr) {
      //       return
      //     }
      //   }
      //   setTimeout(() => {
      //     if (obj.requestId == taobaoCodeRequestId) {
      //       log('换验证码')
      //       Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_CheckCodeImg1")[0].click()'})
      //     }
      //   }, 2000)
      // }
    } else if (obj.requestId == jdBillRequestId) {
      var result = await Network.getResponseBody({
        requestId: obj.requestId
      })
      result = JSON.parse(result.body)
      result.data.forEach(item => {
        if(item.splitName == '已拆单') {
          return
        }
        if (mongoMng.db) {
          mongoMng.db.collection('bill').find({
            orderId: item.orderId
          }).toArray((err, result) => {
            if (err) {
              log(err);
              return;
            }
            if (result.length == 0) {
              log('有新京东订单')
              mongoMng.db.collection('bill').insert([item], (err, result) => {
                if (err) {
                  log(err);
                  return;
                }
              });
            } else {
              mongoMng.db.collection('bill').update({
                orderId: item.orderId
              }, {
                $set: item
              }, (err, result) => {
                if (err) {
                  log(err);
                  return;
                }
              });
            }
          })
        }
      })
      log('获取京东订单结束，释放chrome')
      exports.busy = false
    } else if (obj.requestId == jdCodeRequestId) {
      log('需要输入京东验证码')
      var result = await Network.getResponseBody({
        requestId: obj.requestId
      })
      exports.code = result.body
      exports.codeRequestId = obj.requestId
      exports.codeText = ''
    }
  })
  Page.loadEventFired(async () => {
  })
  Promise.all([Network.enable(), Page.enable(), DOM.enable()]).then(async () => {
    log('chrome connected')
    exports.client = client
    exports.getTaobaoKeyWords = require('./chromeMng/getTaobaoKeyWords')
    exports.getTaobaoItems = require('./chromeMng/getTaobaoItems')
    exports.loginTaobao = require('./chromeMng/loginTaobao')
    exports.getTaobaoAdvLink = require('./chromeMng/getTaobaoAdvLink')
    exports.checkLoginTaobao = require('./chromeMng/checkLoginTaobao')
    exports.loginJd = require('./chromeMng/loginJd')
    exports.getJdAdvLink = require('./chromeMng/getJdAdvLink')
    exports.getJdItems = require('./chromeMng/getJdItems')
    exports.checkLoginJd = require('./chromeMng/checkLoginJd')
    // screenshot(client)
  }).catch(err => {
    log(err);
    client.close();
  });
}

function resolve(client) {
// 0: 加载登录页中
// 1: 登录成功
  var stage = 0

  const {
    Network,
    Page,
    DOM,
    Runtime,
    Emulation
  } = client;
  var requestIds = []
  Network.requestWillBeSent(obj => {
    if (stage == 0) {
      if (obj.request.url.indexOf('http://125.95.19.22/fsweixin/AuthImage') != -1) {
        requestIds[0] = obj.requestId
      } else if (obj.request.url.indexOf('http://125.95.19.22/fsweixin/UserServlet') != -1) {
        requestIds[1] = obj.requestId
      }
    } else if (stage == 5) {
      if (obj.request.url == 'http://125.95.19.22/fsweixin/QueryCarServlet') {
        requestIds[2] = obj.requestId
      }
    }
    // log(obj.request.url);
  });
  Network.loadingFinished(async obj => {
    if (stage == 0) {
      if (obj.requestId == requestIds[0]) {
        var result = await Network.getResponseBody({
          requestId: obj.requestId
        })
        if (result.body == '') {
          await Runtime.evaluate({expression: 'reloadImg()'})
          return
        }
        require('fs').writeFile('/tmp/cgs.jpg', new Buffer(result.body, 'base64'), 'base64', async err => {
          if (err) {
            log(err);
            return
          }
        })
        if (!ocrMng.aipOcr) {
          return
        }
        result = await ocrMng.aipOcr.generalBasic(result.body)
        // result = await aipOcr.accurateBasic(result.body)
        var validateCode = result.words_result[0].words.replace(/[\r\n\s]/gm, '')
        if (validateCode.length != 4) {
          await Runtime.evaluate({expression: 'reloadImg()'})
          return
        }
        result = await DOM.getDocument();
        var rootNodeId = result.root.nodeId
        await Runtime.evaluate({expression: 'document.querySelectorAll("#username")[0].value="440682198906064373"'})
        await Runtime.evaluate({expression: 'document.querySelectorAll("#password")[0].value="123654"'})
        await Runtime.evaluate({expression: 'document.querySelectorAll("#validateCode")[0].value="' + validateCode + '"'})
        await Runtime.evaluate({expression: 'login()'})
      } else if (obj.requestId == requestIds[1]) {
        var result = await Network.getResponseBody({
          requestId: obj.requestId
        })
        if (result.body == '0') {
          stage = 1
        } else {
          setTimeout(() => {
            Runtime.evaluate({expression: 'reloadImg()'})
          }, 1000)
        }
      }
    } else if (stage == 5) {
      if (obj.requestId == requestIds[2]) {
        stage++
        await Runtime.evaluate({expression: 'document.getElementsByTagName("a")[13].click()'})
      }
    }
  })
  Page.loadEventFired(async () => {
    exports.isLoadEventFired = true
    var result = await DOM.getDocument();
    //log(result)
    var rootNodeId = result.root.nodeId
    if (stage == 1) {
      result = await DOM.querySelectorAll({
        nodeId: rootNodeId,
        selector: '#wscgs'
      });
      result = await DOM.getAttributes({
        nodeId: result.nodeIds[0]
      })
      for (var i = 0; i < result.attributes.length; i += 2) {
        if (result.attributes[i] == 'onclick') {
          stage++
          await Runtime.evaluate({expression: result.attributes[i + 1]})
          break
        }
      }
    } else if (stage == 2) {
      stage++
      await Runtime.evaluate({expression: 'document.getElementsByTagName("a")[1].click()'})
    } else if (stage == 3) {
      stage++
      await Runtime.evaluate({expression: 'document.getElementsByTagName("a")[1].click()'})
    } else if (stage == 4) {
      stage++
      await Runtime.evaluate({expression: 'document.getElementsByTagName("a")[2].click()'})
    } else if (stage == 6) {
      result = await DOM.getOuterHTML({
        nodeId: rootNodeId
      })
      if (result.outerHTML.indexOf('没有查询到未处理的交通违法记录!') != -1) {
        log('没有查询到未处理的交通违法记录!')
      }
      exports.busy = false
    }
  });
  Promise.all([Network.enable(), Page.enable(), DOM.enable()]).then(async () => {
    log('chrome connected')
    exports.client = client
    exports.getHtml = require('./chromeMng/getHtml')
  }).catch(err => {
    log(err);
    client.close();
  });
}

exports.busy = false
exports.isLoadEventFired = false
